<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\SoftDeletes;

class Survey extends Model
{
    use SoftDeletes;
    protected $table='surveys';
    protected $guarded=[];
    protected $dates = ['delete_at'];


    //新建调查
    public static function newSurvey($request){
        //字段验证
        $request->validate([
            'project_id'=>'required|numeric',
            'block_name'=>'required',
            'block_area'=>'required|numeric',
            'block_house_num'=>'required|numeric',
            'leader'=>'required',
            'executor'=>'required',
        ]);
        $data['project_id']=$request->project_id;
        $data['block_name']=$request->block_name;
        $data['block_area']=$request->block_area;
        $data['block_house_num']=$request->block_house_num;
        $data['leader']=$request->leader;
        $data['executor']=$request->executor;
        $newSurvey=Survey::create($data);
        if($newSurvey){
            return redirect()->back()->with('status','小主！新建成功！');
        }else{
            $request->session()->flash('project_id', "$request->project_id");
            $request->session()->flash('block_name', "$request->block_name");
            $request->session()->flash('block_area', "$request->block_area");
            $request->session()->flash('block_house_num', "$request->block_house_num");
            $request->session()->flash('leader', "$request->leader");
            $request->session()->flash('executor', "$request->executor");
            return redirect()->back()->with('status','小主！新建失败!');
        }
    }

    //定义调查表和项目表关联关系
    public function project(){
        return $this->belongsTo('App\Models\Project');
    }

    //定义房屋表和调查表关联关系
    public function houses(){
        return $this->hasMany('App\Models\Houses','survey_id','id');
    }

    /*
     * 修改调查
     * */
    public static function updateSurvey($request){
        $data['block_name']=$request->block_name;
        $data['block_area']=$request->block_area;
        $data['block_house_num']=$request->block_house_num;
        $data['leader']=$request->leader;
        $data['executor']=$request->executor;
        $updateSurvey=Survey::where('id',$request->survey_id)->update($data);
        if($updateSurvey){
            return  back()->with('status','修改成功');
        }else{
            return  back()->with('status','调查信息未做任何修改');
        }
    }
}
